<!-- 专区商品 -->
<template>
  <div class="zoneGoods sys-content">
    <page-mod>
      <el-card>
        <div class="query-box">
          <el-form :model="query" inline>
            <el-form-item label="商品名称:">
              <el-input v-model="query.productName" placeholder="请输入商品名称" clearable/>
            </el-form-item>
            <el-form-item label="商品编号:">
              <el-input v-model="query.productCode" placeholder="请输入商品编号" clearable/>
            </el-form-item>
            <el-form-item label="专区:">
              <el-select v-model="query.productZoneId" placeholder="请选择专区" clearable class="zone-select">
                <el-option v-for="item in zoneList" :key="item.productZoneId" :label="item.zoneName" :value="item.productZoneId" />
              </el-select>
            </el-form-item>
          </el-form>
          <div class="btns">
            <el-button icon="Search" color="#16b777" @click="load(1)">查询</el-button>
            <el-button icon="Plus" color="#FFB800" @click="toAddGoods">添加商品</el-button>
            <el-button icon="Refresh" color="#FF5722" @click="resetSearch(true)">重置</el-button>
          </div>
        </div>
      </el-card>
    </page-mod>
    <page-mod title="专区商品数据" icon="Goods" :showBtn="false" :padBottom="false">
      <el-card v-loading="loading" element-loading-text="拼命加载中" >
        <el-table :data="dataList" max-height="493" border>
          <el-table-column label="序号" type="index" align="center" width="60"/>
          <el-table-column label="商品图片" prop="img" align="center">
            <template #default="{row}">
              <div class="img-cell">
                <el-image :src="row.pic + '?x-oss-process=image/resize,m_fill,h_40,w_40'"/>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="商品名称" prop="name" align="center"></el-table-column>
          <el-table-column label="商品编号" prop="productCode" align="center"></el-table-column>
          <el-table-column label="价格（元）" prop="salePrice" align="center"></el-table-column>
          <el-table-column label="SKU信息" prop="title" align="center">
            <template #default="{row}">
              <el-button type="primary" icon="EditPen" circle @click="toViewSku(row)"/>
            </template>
          </el-table-column>
          <el-table-column label="上架状态" prop="enableStatus" align="center">
            <template #default="{row}">
              <el-tag :type="row.enableStatus ? 'success' : 'danger'">{{ row.enableStatus ? '已上架' : '已下架' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="240">
            <template #default="{row}">
              <el-button type="primary" icon="Edit" link @click="toUpdate(row.productId)">编辑</el-button>
              <el-divider direction="vertical" />
              <el-button type="danger" icon="Delete" link @click="doDelete(row.zoneProductId)">删除</el-button>
              <el-divider direction="vertical" />
              <el-button
                :type="row.enableStatus ? 'danger' : 'success'" 
                :icon="row.enableStatus ? 'WarnTriangleFilled' : 'SuccessFilled'"
                link 
                @click="doPublish(row)">
                {{ row.enableStatus ? '下架' : '上架' }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination 
          class="paging"
          v-show="query.total"
          small
          layout="total, sizes, prev, pager, next, jumper" 
          :current-page="query.current" 
          :page-size="query.size"
          :total="query.total"
          @current-change="load"
          @size-change="sizeChange">
        </el-pagination>
      </el-card>
    </page-mod>

    <!-- 选择商品 -->
    <el-dialog v-model="show" title="选择商品" top="10vh" width="72%" center draggable @close="resetForm">
      <div class="search-box">
        <el-form :model="queryGoods" inline size="default" label-width="75px">
          <el-form-item label="商品名称:">
            <el-input v-model="queryGoods.name" placeholder="请输入商品名称" clearable/>
          </el-form-item>
          <el-form-item label="商品编号:">
            <el-input v-model="queryGoods.productCode" placeholder="请输入商品编号" clearable/>
          </el-form-item>
          <el-form-item label="商品分类:">
            <el-select v-model="queryGoods.parentCategoryId" placeholder="请选择商品Ⅰ级分类" clearable class="input-w" @change="loadGoodsType">
              <el-option v-for="item in goodTypesOne" :key="item.productCategoryId" :label="item.name" :value="item.productCategoryId"/>
            </el-select>
            <el-select v-model="queryGoods.subCategoryId" placeholder="请选择商品Ⅱ级分类" clearable class="input-w">
              <el-option v-for="item in goodTypesTwo" :key="item.productCategoryId" :label="item.name" :value="item.productCategoryId"/>
            </el-select>
          </el-form-item>
        </el-form>
        <div class="btns">
          <el-button icon="Search" color="#16b777" @click="loadGoods(1)">查询</el-button>
          <el-button icon="Plus" color="#FFB800" @click="doChoose">选择</el-button>
          <el-button icon="Refresh" color="#FF5722" @click="resetSearch(false)">重置</el-button>
        </div>
      </div>
      <el-table ref="tableRef" :data="goodsList" max-height="493" border>
        <el-table-column type="selection" align="center" width="100" />
        <el-table-column label="商品图片" prop="pic" align="center">
          <template #default="{row}">
            <div class="img-cell">
              <el-image :src="row.pic" :preview-src-list="[row.pic]" preview-teleported/>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="商品名称" prop="name" align="center"></el-table-column>
        <el-table-column label="商品编号" prop="productCode" align="center"></el-table-column>
        <el-table-column label="出厂价" prop="oriPrice" align="center"></el-table-column>
        <el-table-column label="销售价" prop="salePrice" align="center"></el-table-column>
      </el-table>
      <el-pagination 
        class="paging"
        v-show="queryGoods.total"
        small
        layout="total, sizes, prev, pager, next, jumper" 
        :current-page="queryGoods.current" 
        :page-size="queryGoods.size"
        :total="queryGoods.total"
        @current-change="loadGoods"
        @size-change="sizeChangeGoods">
      </el-pagination>
    </el-dialog>

    <!-- 查看SKU -->
    <el-dialog v-model="skuShow" :title="title" top="10vh" width="60%" draggable>
      <el-table :data="skuList" :header-cell-style="{fontSize:'12px'}" max-height="400" border size="small">
        <el-table-column v-for="item in skuTableHeader" :key="item.prop" :label="item.label" :prop="item.prop" :fixed="item.prop.indexOf('specs') !== -1" align="center">
          <template #default="{row}">
            <div v-if="item.prop === 'skuPic'" class="sku-pic">
              <upload-img v-model="row.skuPic" width="40" height="40" iconSize="20" useScan></upload-img>
            </div>
            <span v-else-if="/^\d+$/.test(item.prop)">{{ row[item.prop] }}</span>
            <el-input v-else v-model="row[item.prop]" type="number" placeholder="请输入" size="small"/>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button type="primary" size="default" @click="doUpdateSku">保存</el-button>
        <el-button size="default" @click="skuShow = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 新增专区商品 -->
    <el-drawer 
      v-model="addShow" 
      :with-header="false" 
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :destroy-on-close="true" 
      size="89.6%">
      <add-zone-goods v-if="handleType" @close="doChose"></add-zone-goods>
      <edit-zone-goods v-else @close="doChose"></edit-zone-goods>
    </el-drawer>
  </div>
</template>

<script setup name="zoneGoods">
  import addZoneGoods from './add/index.vue'
  import editZoneGoods from './edit/index.vue'
  import { 
    cdZoneGoodsApi, 
    getZoneGoodsListPagesApi, 
    updateZoneGoodsStatusApi, 
    getGoodsTypeListApi,
    getZoneListApi, 
    getGoodsListPagesApi, 
    getGoodsSkuInfoApi, 
    updateGoodsSkuApi
  } from '@/api/api'
  import { ref, reactive, toRefs, getCurrentInstance, onActivated } from 'vue'
  import { useStore } from 'vuex' 

  const store = useStore()  

  // 获取注册的全局实列
  const currentThis = getCurrentInstance().appContext.config.globalProperties
  const tableRef = ref(null)
  
  const currentData = reactive({
    loading: false,
    show: false,
    addShow: false,
    skuShow: false,
    handleType: false,
    query: {
      productName: '',
      productCode: '',
      productZoneId: '',
      current: 1,
      size: 20,
      total: 0
    },
    queryGoods: {
      name: '',
      productCode: '',
      parentCategoryId: '',
      subCategoryId: '',
      enableStatus: '1',
      productType: '0',
      current: 1,
      size: 20,
      total: 0
    },
    dataList: [],
    goodsList: [],
    title: '',
    skuTableHeader: [],
    skuList: [],
    goodTypesOne: [],
    goodTypesTwo: [],
    zoneList: []
  })
  let {loading, show, addShow, skuShow, handleType, query, queryGoods, dataList, goodsList, form, title, skuTableHeader, skuList, goodTypesOne, goodTypesTwo, zoneList} = toRefs(currentData)

  // 查询专区商品
  function load(page) {
    currentData.loading = true
    currentData.query.current = page
    getZoneGoodsListPagesApi(currentData.query).then(res => {
      currentData.loading = false
      if(res.code === '200') {
        currentData.dataList = res.data.pages
        currentData.query.total = res.data.total
      } else {
        currentThis.$message.error(res.message)
      }
    })
  }

  // 初始化专区下拉数据
  loadZones()
  function loadZones() {
    getZoneListApi().then(res => {
      if(res.code === '200') {
        currentData.zoneList = res.data
      } else {
        currentThis.$message.error(res.message)
      }
    })
  }

  // 查询商品，可以被设置为专区商品的商品
  function loadGoods(page) {
    currentData.queryGoods.current = page
    getGoodsListPagesApi(currentData.queryGoods).then(res => {
      if(res.code === '200') {
        currentData.goodsList = res.data.pages
        currentData.queryGoods.total = res.data.total
      } else {
        currentThis.$message.error(res.message)
      }
    })
  }

  /**
   * 查询商品分类下拉列表数据
   * parentId为0或不传时候，查询的是一级商品分类，其他情况查询是二级商品分类
   */
  function loadGoodsType(parentId) {
    if(!parentId) {
      currentData.goodTypesTwo = []
      currentData.queryGoods.subCategoryId = ''
      return
    }
    getGoodsTypeListApi({parentId: parentId}).then(res => {
      if(res.code === '200') {
        if(parentId === '0') {
          currentData.goodTypesOne = res.data
        } else {
          currentData.goodTypesTwo = res.data
          currentData.queryGoods.subCategoryId = ''
        }
      }
    })
  }

  // 添加专区商品弹窗
  function toAddGoods() {
    loadGoods(1)
    currentData.show = true
  }

  // 选择商品，复制该商品设置为抵扣商品
  function doChoose() {
    let chooseGoods = tableRef.value.getSelectionRows()
    if(chooseGoods.length === 0) {
      currentThis.$message.error(`请先勾选商品`)
      return 
    }
    if(chooseGoods.length > 1) {
      currentThis.$message.error(`只能选择一种商品`)
      return 
    }
    store.commit('productId', chooseGoods[0].productId)
    tableRef.value.clearSelection()
    currentData.handleType = true
    currentData.show = false
    currentData.addShow = true
  }

  // 修改弹窗
  function toUpdate(productId) {
    store.commit('productId', productId)
    currentData.handleType = false
    currentData.addShow = true
  }

  // 删除专区商品
  function doDelete(productId) {
    currentThis.$messageBox.confirm('确认删除吗？').then(() => {
      let loading = currentThis.$loading('删除中，请耐心等待')
      cdZoneGoodsApi('delete', { id: productId }).then(res => {
        loading.close()
        if(res.code === '200') {
          currentThis.$message.success(res.message)
          load(currentData.query.current)
        } else {
          currentThis.$message.error(res.message)
        }
      })
    }).catch(() => {})
  }

  // 上架或下架
  function doPublish(e) {
    currentThis.$messageBox.confirm(`确认${e.enableStatus ? '下架' : '上架'}吗？`).then(() => {
      const loading = currentThis.$loading('正在处理，请耐心等待')
      updateZoneGoodsStatusApi(e.zoneProductId, e.enableStatus ? 0 : 1).then(res => {
        loading.close()
        if(res.code === '200') {
          load(currentData.query.current)
          currentThis.$message.success(res.message)
        } else {
          currentThis.$message.error(res.message)
        }
      })
    }).catch(() => {})
  }

  // 查看sku信息
  function toViewSku(e) {
    currentData.title = `商品编号：${e.productCode}`
    getGoodsSkuInfoApi(e.productId).then(res => {
      if(res.code === '200') {
        let tableHeader = [
          {label: 'SKU图标', prop: 'skuPic'},
          {label: '出厂价', prop: 'oriPrice'},
          {label: '销售价', prop: 'salePrice'},
          {label: '库存', prop: 'stocks'},
          {label: '库存预警值', prop: 'lowStock'},
          {label: '赠送积分', prop: 'giftPoint'},
          {label: '金积分', prop: 'agentPoint'}
        ]
        res.data.headList.forEach((item, index) => {
          tableHeader.splice(index, 0, {label: item.name, prop: item.attributeId})
        })
        currentData.skuTableHeader = tableHeader
        currentData.skuList = res.data.infoList
        currentData.skuShow = true
      } else {
        currentThis.$message.error(res.message)
      }
    })
  }

  // 修改商品sku
  function doUpdateSku() {
    currentThis.$messageBox.confirm(`确认修改吗？`).then(() => {
      let loading = currentThis.$loading('修改中，请耐心等待')
      updateGoodsSkuApi(currentData.skuList).then(res => {
        loading.close()
        if(res.code === '200') {
          currentData.skuShow = false
          load(currentData.query.current)
          currentThis.$message.success(res.message)
        } else {
          currentThis.$message.error(res.message)
        }
      })
    }).catch(() => {})
  }

  
  // 关闭新增，编辑商品弹窗
  function doChose() {
    load(currentData.query.current)
    currentData.addShow = false
  }

  // 重置查询
  function resetSearch(e) {
    if(e) {
      currentData.query.productName = ''
      currentData.query.productCode = ''
      currentData.query.productZoneId = ''
      load(1)
    } else {
      resetForm()
    }
  }
  // 选择商品弹窗重置查询参数
  function resetForm() {
    currentData.queryGoods.name = ''
    currentData.queryGoods.productCode = ''
    currentData.queryGoods.parentCategoryId = ''
    currentData.queryGoods.subCategoryId = ''
    loadGoods(1)
  }

  // 分页每页显示条数改变执行
  function sizeChangeGoods() {
    currentData.queryGoods.size = size
    loadGoods(1)
  }
  function sizeChange(size) {
    currentData.query.size = size
    load(1)
  }

  onActivated(() => {
    load(currentData.query.current)
    loadGoodsType('0') // 初始商品分类的一级分类
  })
</script>

<style lang="less" scoped>
.zoneGoods{
  :deep(.zone-select.el-select){
    .el-input{
      width: 200px !important;
    }
  }
  :deep(.el-table){
    .img-cell{
      display: flex;
      justify-content: center;
      align-items: center;
      .el-image{
        width: 40px; 
        height: 40px;
        border-radius: 5px;
      }
    }
  }
  :deep(.el-drawer){
    .el-drawer__body{
      padding: 0 !important;
    }
  }
  :deep(.el-dialog){
    .el-dialog__body{
      max-height: 600px;
      overflow: hidden auto;
      .search-box{
        display: flex;
        justify-content: space-between;
        .el-input{
          width: 150px;
        }
        .input-w.el-select{
          .el-input{
            width: 180px;
          }
          &:last-child{
            margin-left: 10px;
          }
        }
        >.btns{
          width: 25%;
          text-align: right;
          >.el-button{
            color: #ffffff !important;
          }
        }
      }
      .sku-pic{
        display: flex;
        justify-content: center;
        align-items: center;
      }
    }
  }
}
</style>